import React, {FC, forwardRef, useEffect, useState, useImperativeHandle, PropsWithRef} from "react";
import { Form, Input, Button, Card, Checkbox, message, Col, Row, Image, Flex, Modal, ModalFuncProps } from 'antd';
import { addScene } from '../../services';
import { setSession } from '@bastet/utils';
import { useNavigate } from "react-router-dom";


const AddSceneModal: FC<PropsWithRef<any>> = forwardRef((props, ref) => {
  const [loading, setLoading] = useState<boolean>();
  const [visible, setVisible] = useState<boolean>();
  const navigate = useNavigate();
  const [form] = Form.useForm();

  useImperativeHandle(ref, () => ({
    setVisible
  }))

  const routeToHome = (sceneId: any) => {
    // 跳转到对应场景
    navigate(`/scene/${sceneId}`)
  }

  const onOk = () => {
    // setLoading(true)

    form.validateFields().catch(console.error).then((fields: any) => {
      addScene(fields).then(({ data, code }: any) => {
        if (code === 200) {
          message.success('新增场景成功！');
          routeToHome(data.id)
        }
      }).finally(() => {
        setLoading(false)
      });
      console.log(fields)
    })

  };

  const onCancel = () => {
    setVisible(false);
  };

  console.log(visible, ref)
  return (
    <Modal
      title="新增场景"
      className="add-scene-modal"
      open={visible}
      onOk={onOk}
      onCancel={onCancel}
      confirmLoading={loading}
      { ...props }
    >
      <Form
        form={form}
        name="add_scene"
        className="add-scene-form"
      >
        <Form.Item
          label="场景名称"
          name="name"
          rules={[{ required: true, message: '场景名称不能为空!' }]}
        >
          <Input placeholder="请输入场景名称" />
        </Form.Item>
        <Form.Item label="场景名称" name="description">
          <Input.TextArea placeholder="描述" />
        </Form.Item>
      </Form>
    </Modal>
  )
})

export default AddSceneModal